package com.iap.admin.view.vector.code
{
	import com.iap.admin.signal.VectorRequestSignal;
	import com.iap.admin.signal.VectorTagRequestSignal;
	import com.iap.admin.view.code.EditViewCode;
	import com.iap.admin.view.vector.VectorEditView;
	import com.iap.admin.view.vector.VectorImageManagerControl;
	import com.iap.app.AppText;
	import com.iap.app.data.AppData;
	import com.iap.app.model.ServiceResponse;
	import com.iap.app.util.FormUtils;
	import com.iap.common.model.Tag;
	import com.iap.common.model.VectorImage;
	import com.iap.common.model.VectorModel;
	import com.iap.common.model.VectorTag;
	import com.iap.common.signal.TagRequestSignal;
	import com.iap.common.translator.VectorTagTranslator;
	
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.utils.getQualifiedClassName;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	import mx.validators.StringValidator;
	
	import org.osflash.signals.Signal;

	public class VectorEditViewCode extends EditViewCode
	{
		public static const CANCEL_NAME:String = "VectorCreate.Cancel";
		public static const SAVE_NAME:String = "VectorCreate.Save";
		public static const DELETE_NAME:String = "VectorCreate.Delete";
		
		public var onSubmit:VectorRequestSignal = new VectorRequestSignal();
		public var onVectorTagRequest:VectorTagRequestSignal = new VectorTagRequestSignal();
		
		private var nameValidator:StringValidator;
		private var view:VectorEditView;
		public var vectorTags:Array;
		
		public function VectorEditViewCode()
		{
			super();
		}

		protected function initView(view:VectorEditView):void
		{
			this.view = view;
			addListener();
			initValidators();
			resetFocus();
			onReady.dispatch("ready");
		}
		
		private function initValidators():void
		{
			nameValidator = new StringValidator();
			
			nameValidator.source = view.nameForm;
			nameValidator.property = "text";
			nameValidator.required = true;
			nameValidator.maxLength = 100;
			
			validateData.push(nameValidator);
		}
		
		private function addListener():void
		{
			view.nameForm.addEventListener(Event.CHANGE, validateForm);
			view.nameForm.addEventListener(FocusEvent.FOCUS_OUT, nameFocusOut);
		}
		
		private function nameFocusOut(event:Event):void 
		{
			if(formIsValid)
				submit();
		}

		private function removeListener():void
		{
			view.nameForm.removeEventListener(Event.CHANGE, validateForm);
		}
		
		private function resetFocus():void
		{
		}
		
		public function submit():void 
		{
			model ||= new VectorModel();
			if((model as VectorModel).name == null)
				(model as VectorModel).name = "";
			model = FormUtils.fillObjectFromControls(view, model, FORM_PREFIX);
			setVectorImages();
			setVectorTags();
			onSubmit.dispatch(model, VectorRequestSignal.SAVE);
		}
		
		protected function remove():void 
		{
			onSubmit.dispatch(model, VectorRequestSignal.VALID_REMOVE);
		}
		
		public function removeVector(needConfirmation:Boolean):void
		{
			if(needConfirmation)
			{
				showConfirm("El Vector se encuentra usado en otros recursos. Desea borrarlo igualmente ?", function():void{
					onSubmit.dispatch(model, VectorRequestSignal.DELETE);
				});
			} else {
				onSubmit.dispatch(model, VectorRequestSignal.DELETE);
			}
		}
		
		public override function fill(model:Object):void
		{
			super.fill(model);
			view.setCurrentState("edit");
			var items:Array = (model as VectorModel).vectorImages;
			view.preview.setSource(items);
			view.imagecontrol.setSource(items);
			fillAutoComplete();
		}
		
		private function fillAutoComplete():void
		{
			vectorTags = (model as VectorModel).vectorTags;
			var list:Array = [];
			for each(var item:VectorTag in vectorTags)
			{
				list.push(item.tag);
			}
			view.tagAutoComplete.selectedItems = new ArrayCollection(list);
		}
		
		private function setVectorImages():void
		{
			var vectorModel:VectorModel = (model as VectorModel);
			var imageControl:VectorImageManagerControl = view.imagecontrol;
			var list:Array = imageControl ? 
				imageControl.grid.dataProvider.toArray() : [];
			for each(var item:VectorImage in list)
			{
				item.vectorId = vectorModel.id;
			}
			vectorModel.vectorImages = list;
		}

		private function setVectorTags():void
		{
			var vectorModel:VectorModel = (model as VectorModel);
			var selectedItems:Array = (view.tagAutoComplete.selectedItems) ? 
				view.tagAutoComplete.selectedItems.toArray() : [];
			var list:Array = [];
			for each(var item:Object in selectedItems)
			{
				list.push(getVectorTagFromSelectedItem(item));
			}
			for each(var vitem2:VectorTag in list)
			{
				for each(var vitem:VectorTag in vectorModel.vectorTags)
				{
					if(vitem.tag.id == vitem2.tag.id)
					{
						vitem2.id = vitem.id;
					}
				}
			}
			vectorModel.vectorTags = list;
		}
		
		private function getVectorTagFromSelectedItem(item:Object):VectorTag
		{
			var vectorModel:VectorModel = (model as VectorModel);
			var tag:Tag;
			var vectorTag:VectorTag = new VectorTag();
			vectorTag.vectorId = vectorModel.id;
			if(getQualifiedClassName(item) == "String")
			{
				tag = new Tag();
				tag.name = item as String;
			} else {
				tag = item as Tag;
			}
			vectorTag.tag = tag;
			for each(var vitem:VectorTag in vectorModel.vectorTags)
			{
				if(vitem.tag.id == tag.id)
				{
					vectorTag.id = vitem.id;
				}
			}
			return vectorTag;
		}
		
		private function getDeletedItem(items:Array):VectorTag
		{
			var found:VectorTag = null;
			var vectorModel:VectorModel = (model as VectorModel);
			var trythis:VectorTag;
			var selectedItem:VectorTag;
			for each(var vtag:VectorTag in vectorModel.vectorTags)
			{
				trythis = vtag;
				for each(var item:Object in items)
				{
					selectedItem = getVectorTagFromSelectedItem(item);
					if(vtag.tag.id == selectedItem.tag.id)
					{
						trythis = null;
					}
				}
				if(trythis != null) found = trythis;
			}
			return found;
		}

		protected function handleAutoCompleteChange():void
		{
			var vectorTagModel:VectorTag = getVectorTagFromSelectedItem(view.tagAutoComplete.selectedItem);
			onVectorTagRequest.dispatch(vectorTagModel, VectorTagRequestSignal.SAVE);
		}
		
		protected function handleAutoCompleteRemove():void
		{
			var vectorTagModel:VectorTag = getVectorTagFromSelectedItem(view.tagAutoComplete.removedItem);
			onVectorTagRequest.dispatch(vectorTagModel, VectorTagRequestSignal.DELETE);
		}

		public function setVectorTagResponse(response:ServiceResponse):void
		{
			var vectorTag:VectorTag = response.result as VectorTag;
			var vectorModel:VectorModel = (model as VectorModel);
			if(response.task != VectorTagRequestSignal.DELETE)
			{
				vectorModel.vectorTags.push(vectorTag);
			} else 
			{
				vectorModel.vectorTags = removeVectorTag(vectorModel.vectorTags, vectorTag);
			}
			fillAutoComplete();
		}
		
		private function removeVectorTag(list:Array, deletedItem:VectorTag):Array
		{
			var newlist:Array = [];
			for each(var item:VectorTag in list)
			{
				if(item.id != deletedItem.id)
				{
					newlist.push(item);
				}
			}
			return newlist;
		}

		private function showConfirm(message:String, action:Function):void
		{
			var alert:Alert = Alert.show(message, AppText.CONFIRM_DELETE_TITLE, Alert.YES|Alert.NO, null, null, null, Alert.NO);
			var closeFnc:Function;
			alert.addEventListener(CloseEvent.CLOSE, closeFnc = function(evt:CloseEvent):void{
				alert.removeEventListener(CloseEvent.CLOSE, closeFnc);				
				if (evt.detail == Alert.YES)
				{
					action();
				}
			});
		}
	}
}